{% extends 'base.html' %}
{% load static %}
{% load i18n %}

{% block custom_head_css_js %}
    <link href="{% static "css/plugins/select2/select2.min.css" %}" rel="stylesheet">
    <script src="{% static "js/plugins/select2/select2.full.min.js" %}"></script>
{% endblock %}
{% block content %}
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="panel-options">
                        <ul class="nav nav-tabs">
                            <li class="active"><a href="" class="text-center"><i class="fa fa-laptop"></i> {% trans 'Detail' %} </a></li>
                            <li class="pull-right">
                                <a class="btn btn-outline btn-default" href="{% url 'devm:device-group-update' pk=device_group.id %}"><i class="fa fa-edit"></i>Update</a>
                            </li>
                        </ul>
                    </div>
                    <div class="tab-content">
                        <div class="col-sm-7" style="padding-left: 0">
                            <div class="ibox float-e-margins">
                                <div class="ibox-title">
                                    <span style="float: left"></span>{% trans 'Device List of ' %} <b>{{ device_group.name }}</b></span>
                                    <div class="ibox-tools">
                                        <a class="collapse-link">
                                            <i class="fa fa-chevron-up"></i>
                                        </a>
                                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                                            <i class="fa fa-wrench"></i>
                                        </a>
                                        <ul class="dropdown-menu dropdown-user">
                                        </ul>
                                        <a class="close-link">
                                            <i class="fa fa-times"></i>
                                        </a>
                                    </div>
                                </div>
                                <div class="ibox-content">
                                    <table class="table table-hover " id="asset_list_table" >
                                        <thead>
                                            <tr>
                                                <th>{% trans 'name' %}</th>
                                                <th>{% trans 'Type' %}</th>
                                                <th>{% trans 'device_addr' %}</th>
	                                              <th>{% trans 'comment' %}</th>
                                                <th>{% trans 'device_stat' %}</th>
	                                              <th>{% trans 'Action' %}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="col-sm-5" style="padding-left: 0;padding-right: 0">
                            <div class="panel panel-primary">
                                <div class="panel-heading">
                                    <i class="fa fa-info-circle"></i> {% trans 'Push system users' %}
                                </div>
                                <div class="panel-body">
                                    <table class="table">
                                        <tbody>
                                        <form>
                                            <tr class="no-borders-tr">
                                                <td colspan="2">
                                                    <select data-placeholder="{% trans 'Select system users' %}" class="select2 system-user-select" style="width: 100%" multiple="" tabindex="4">
                                                        {% for system_user in system_users %}
                                                            <option value="{{ system_user.id }}"> {{ system_user.name }} </option>
                                                        {% endfor %}
                                                    </select>
                                                </td>
                                            </tr>
                                            <tr class="no-borders-tr">
                                                <td colspan="2">
                                                    <button type="button" class="btn btn-primary btn-sm btn-push-system-user">{% trans 'Push' %}</button>
                                                </td>
                                            </tr>
                                        </form>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{#    </div>#}

{% endblock %}
{% block custom_foot_js %}
<script>
  iotserver.assets_selected = {};
  function updateGroupAssets(assets) {
    var the_url = "{}";
    var body = {
      assets: Object.assign([], assets)
    };
    var $data_table = $("#asset_list_table").DataTable();
    var success = function(data) {
      $('.select2-selection__rendered').empty();
      $.map(iotserver.assets_selected, function(asset_ip, index) {
        $('#opt_' + index).remove();
        $data_table.ajax.reload();
      });
      iotserver.groups_selected = {};
    };
    APIUpdateAttr({
      url: the_url,
      body: JSON.stringify(body),
      method: 'PUT',
      success: success
    });
  }

function leaveGroup(obj, name, url, data) {
    function doDelete() {
        var body = data;
        var success = function() {
            swal('Deleted!', "[ "+name+"]"+" has been deleted ", "success");
            $(obj).parent().parent().remove();
        };
        var fail = function() {
            swal("Failed", "Delete"+"[ "+name+" ]"+"failed", "error");
        };
        APIUpdateAttr({
            url: url,
            body: JSON.stringify(body),
            method: 'PATCH',
            success: success,
            error: fail
        });
    }
    swal({
        title: 'Are you sure delete ?',
        text: " [" + name + "] ",
        type: "warning",
        showCancelButton: true,
        cancelButtonText: 'Cancel',
        confirmButtonColor: "#DD6B55",
        confirmButtonText: 'Confirm',
        closeOnConfirm: false
    }, function () {
        doDelete()
    });
}



Array.prototype.remove = function(val) {
	var index = this.indexOf(val);
		if (index > -1) {
		this.splice(index, 1);
	}
};

Array.prototype.unique = function(){
	var res = [];
	var json = {};
 	for(var i = 0; i < this.length; i++){
  		if(!json[this[i]]){
   			res.push(this[i]);
   			json[this[i]] = 1;
  		}
 	}
 	return res;
};

$(document).ready(function () {
	$('.select2').select2();

  $('.select2.asset-select').select2()
    .on('select2:select', function(evt) {
      var data = evt.params.data;
      iotserver.assets_selected[data.id] = data.text;
      console.log(iotserver.assets_selected)
    })
    .on('select2:unselect', function(evt) {
      var data = evt.params.data;
      delete iotserver.assets_selected[data.id]
    });

	var options = {
		ele: $('#asset_list_table'),
		buttons: [],
		order: [],
		columnDefs: [
			{targets: 0, createdCell: function (td, cellData, rowData) {
				var detail_btn = '<a href="{% url "devm:device-detail" pk=DEFAULT_PK %}" data-aid="'+rowData.id+'">' + cellData + '</a>';
				$(td).html(detail_btn.replace('{{ DEFAULT_PK }}', rowData.id));
			}},
			{targets: 4, createdCell: function (td, cellData) {
				if (!cellData) {
					$(td).html('<i class="fa fa-times text-danger"></i>')
				} else {
					$(td).html('<i class="fa fa-check text-navy"></i>')
				}
			}},
			{targets: 5, createdCell: function (td, cellData, rowData) {
				var update_btn = '<a href="{% url "devm:device-update" pk=DEFAULT_PK %}" class="btn btn-xs btn-info">{% trans "Update" %}</a>'.replace('{{ DEFAULT_PK }}', rowData.id);
				var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn_asset_delete" data-aid="{{ DEFAULT_PK }}">{% trans "Remove" %}</a>'.replace('{{ DEFAULT_PK }}', rowData.id);
				$(td).html(update_btn + del_btn)
			}}
		],
		ajax_url: '{% url "api-devm:device-list" %}?device_group_id={{ device_group.id }}',
		columns: [{data: "name" }, {data: "get_type_display" }, {data: "device_addr" },
			{data: "comment" }, {data: "is_active" }, {data: "id"}],
		op_html: $('#actions').html()
	};
	iotserver.initDataTable(options);
})

.on('click', ".btn-asset-group-add-asset", function () {
  if (Object.keys(iotserver.assets_selected).length === 0) {
    return false;
  }

  updateGroupAssets(iotserver.assets_selected);

})

.on('click', '.btn-push-system-user', function () {
    var data = $('.system-user-select').select2();
    var system_id = data.val()[0];
    if (!system_id) {
        return false
    }
    pushSystemUser(system_id)
})



</script>
{% endblock %}
